package net.sf.jOpinionPoll.tag.security;

import java.io.IOException;

import javax.el.ELException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;

import net.sf.jOpinionPoll.miscellaneous.JOPUtil;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.FaceletException;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.TagHandler;

public final class HasCredentialHandler extends TagHandler {
    private TagAttribute m_TagAttributeRules;
    public HasCredentialHandler(TagConfig tagConfig) {
        super(tagConfig);
        setRules(getRequiredAttribute("rules"));
    }
    
    @Override
	public void apply(FaceletContext ctx, UIComponent parentComp)
			throws IOException, FacesException, FaceletException, ELException {
		
		String[] roles = getRules().getValue(ctx).split(",");
		
		for (int i = 0; i < roles.length; i++) {
			if (roles[i].endsWith(" ") || roles[i].startsWith(" ")) {
				roles[i] = roles[i].trim();
			}
		}
        
		if (JOPUtil.hasRole(roles)) {
			this.nextHandler.apply(ctx, parentComp);
            return;
		}
	}
    
    public TagAttribute getRules() {
        return m_TagAttributeRules;
    }
    
    public void setRules(TagAttribute rules) {
        m_TagAttributeRules = rules;
    }
}